﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using zichan.Models;

namespace zichan.Controllers
{
        //[RouteArea("Admin")]
        public class AccountController : Controller
        {

            // GET: Admin/Account
            [Route("~/account/login")]
            public ActionResult Login(string returnUrl)
            {
                ViewBag.returnUrl = returnUrl;
                return View();
            }

            [Route("~/account/login")]
            [HttpPost]
            //[ValidateAntiForgeryToken]
            public ActionResult Login(LoginViewModel model, string returnUrl)
            {
                if (!ModelState.IsValid)
                    return View();

                if (Session["admin_code"] != null && model.Verifycode.ToLower() != Session["admin_code"].ToString())
                {
                    ModelState.Clear();//才会根据model的内容更新表单，验证码才能清空
                    model.Verifycode = "";//清空验证码
                    ModelState.AddModelError("Verifycode", "验证码错误");
                    return View(model);
                }

                Dictionary<string, string> kv = new Dictionary<string, string>();
                kv.Add("username", model.UserName);
                kv.Add("passwd", model.Password);


                XmispAuth auth = new XmispAuth(ConfigurationManager.AppSettings["HKey"], ConfigurationManager.AppSettings["Key"]);
                string result = auth.Post(kv, "http://" + ConfigurationManager.AppSettings["RemoteUrl"] + "/staff/check");
                JToken jk = (JToken)JsonConvert.DeserializeObject(result);
                JToken jtcode = jk["code"];
                if (jtcode != null)
                {
                    ModelState.Clear();//才会根据model的内容更新表单，验证码才能清空
                    model.Verifycode = "";//清空验证码
                    TempData["error"] = jk["message"].ToString();
                    return View(model);
                }

                ////第一次登录自动加入数据库中
                int staff_id = Convert.ToInt32(jk["staff_id"]);
                //string email = jk["email"].ToString();
                string name = jk["name"].ToString();

                //string department_name = jk["department_name"].ToString();
                //Staff staff = new Staff() { Id = staff_id, Name = name, Email = email, DepartmentName = department_name, Status = (int)StaffStatus.Normal };
                //StaffService.StaffAdd(staff);

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, staff_id + ":" + name, DateTime.Now, DateTime.Now.AddHours(3), false, "admin");
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                cookie.HttpOnly = true;
                Response.Cookies.Add(cookie);

                return RedirectToLocal(returnUrl);
            }


            //
            // POST: /Account/LogOff
            [Route("~/account/Logout")]
            //[HttpPost]
            //[ValidateAntiForgeryToken]
            public ActionResult LogOut()
            {
                FormsAuthentication.SignOut();
                Session.Abandon();
                return RedirectToAction("Login", "Account");
            }

            private ActionResult RedirectToLocal(string returnUrl)
            {

                if (Url.IsLocalUrl(returnUrl))
                    return Redirect(returnUrl);
                else
                    return RedirectToAction("Index", "Home");
            }

        }
    }
